#!/bin/bash
targeturl=''
targetenv=''
versiontag=''
database=''


###################################################################
#收集环境信息
echo "请选择您想部署的镜像仓库:"
echo "d, 表示您将部署至开发环境"
echo "t, 表示您将部署至测试环境"
echo "p, 表示您将部署至正式环境"
read -p "请选择: " targetenv

if [ $targetenv != "d" ] && [ $targetenv != "t" ] && [ $targetenv != "p" ]; then
  echo 'bye'
  exit 1
fi

###################################################################
#收集标识信息
read -p "请从a-z字母中输入一个字母标识: " versiontag


###################################################################
#收集数据库信息
echo "请选择您想对接的数据库环境:"
echo "d, 表示您将对接至开发数据库"
echo "t, 表示您将对接至测试数据库"
echo "p, 表示您将对接至正式数据库"
read -p "请选择: " database

if [ $database != "d" ] && [ $database != "t" ] && [ $database != "p" ]; then
  echo 'bye'
  exit 1
fi


#开始制做镜像
echo "正在生成镜像文件，这可能需要一些时间，请稍后"

if [ $database = "d" ]; then
  echo '设置连接测试数据库的环境变量'
  docker build -t backend-dev --iidfile imageid.txt -f DockerfileDev .
fi

if [ $database = "t" ]; then
  echo '设置连接测试数据库的环境变量'
  docker build -t backend-test --iidfile imageid.txt -f DockerfileTest .
fi

if [ $database = "p" ]; then
  echo '设置连接正式数据库的环境变量'
  docker build -t backend-prod --iidfile imageid.txt -f DockerfileProd .
fi

echo "收集镜像ID："
imageid=$(head -n 1 < imageid.txt| cut -d':' -f 2)

# echo "对接数据库为"
#开始部署
versiontag=$(date "+%Y%m%d$versiontag")

if [ $targetenv = "d" ]; then
  echo '开始部署开发环境镜像'
  versiontag=dev-$versiontag
  echo "标记准备发布的镜像文件"
  docker tag $imageid registry.cn-shanghai.aliyuncs.com/well-talent/django-backend-dev:$versiontag
  echo "开始推送镜像文件"
  docker push registry.cn-shanghai.aliyuncs.com/well-talent/django-backend-dev:$versiontag
fi

if [ $targetenv = "t" ]; then
  echo '开始部署测试环境镜像'
  versiontag=test-$versiontag
  echo "标记准备发布的镜像文件"
  docker tag $imageid registry.cn-shanghai.aliyuncs.com/well-talent/django-backend-test:$versiontag
  echo "开始推送镜像文件"
  docker push registry.cn-shanghai.aliyuncs.com/well-talent/django-backend-test:$versiontag
fi

if [ $targetenv = "p" ]; then
  echo '开始部署正式环境镜像'

  echo "标记准备发布的镜像文件"
  # docker tag $imageid registry.cn-shanghai.aliyuncs.com/well-talent/django-prod:$versiontag
 docker tag $imageid registry.cn-shanghai.aliyuncs.com/well-talent/django-backend:$versiontag
  echo "开始推送镜像文件"
  # docker push registry.cn-shanghai.aliyuncs.com/well-talent/django-prod:$versiontag
  docker push registry.cn-shanghai.aliyuncs.com/well-talent/django-backend:$versiontag
fi

rm imageid.txt
echo '清理本地镜像文件'
docker rmi $imageid -f

echo $versiontag'部署完成'
